package com.gcstorage.tvdev.ui

import android.annotation.SuppressLint
import android.os.CountDownTimer
import android.view.KeyEvent
import android.view.View
import androidx.core.view.isVisible
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.gcstorage.tvdev.R
import com.gcstorage.tvdev.base.BaseActivity
import com.gcstorage.tvdev.bean.TvTabBean
import com.gcstorage.tvdev.constants.ARouterPaths
import com.gcstorage.tvdev.constants.AppConstant
import com.gcstorage.tvdev.constants.LogCat
import com.gcstorage.tvdev.databinding.ActivityTvMainBinding
import com.gcstorage.tvdev.net.ApiAddress
import com.gcstorage.tvdev.net.HttpClient
import com.gcstorage.tvdev.net.RxObserver
import com.gcstorage.tvdev.ui.fragment.WebWorkFragment
import com.gcstorage.tvdev.util.GsonUtils
import com.gcstorage.tvdev.util.JumpHelper
import com.gcstorage.tvdev.view.pop.NoticePopupWindow
import com.gcstorage.tvdev.view.tv.TvTabLayout
import com.google.gson.JsonElement
import com.lxj.xpopup.XPopup


/**
 *@author: liangkun
 *@date: 2022/5/13
 *@des:
 */
@Route(path = ARouterPaths.TV_APP_MAIN)
class TvMainActivity : BaseActivity() {
    private lateinit var binding: ActivityTvMainBinding
    private val THOUSANDS_URL =
        "%s/rb/vue/thousands"
    private var countDownTimer: CountDownTimer? = null
    private lateinit var fragment: WebWorkFragment
    private var tabList = mutableListOf<TvTabBean>()


    override fun getRootView(): View {
        binding = ActivityTvMainBinding.inflate(layoutInflater)
        return binding.root
    }


    override fun initView() {
        val transaction = supportFragmentManager.beginTransaction()
        val businessUrl: String = String.format(
            THOUSANDS_URL,
            AppConstant.getApiAddress(),
        )
        LogUtils.d(LogCat.LOG_COMMONON + " businessUrl $businessUrl ")
        fragment = WebWorkFragment.newInstanceUrl(businessUrl)
        transaction.add(R.id.content, fragment, "WebWorkFragment")
        transaction.commit()
//        initTab(tabList)
        initCountDown()
    }

    /**
     * CountDownTimer 实现倒计时
     */
    private fun initCountDown() {
        if (countDownTimer != null) {
            countDownTimer?.cancel()
        }
        countDownTimer = object : CountDownTimer(
            20000, 1000
        ) {
            @SuppressLint("SimpleDateFormat")
            override fun onTick(millisUntilFinished: Long) {
                //单位秒
                val second: Long = millisUntilFinished / 1000
                LogUtils.d(LogCat.LOG_COMMONON + " 倒计时 $second")
            }

            override fun onFinish() {
                changeTabState(false)
                cancel()
            }
        }
        countDownTimer?.start()
    }

    private fun changeTabState(isShow: Boolean) {
        binding.tablayout.visibility = if (isShow) View.VISIBLE else View.GONE
        binding.shapeLayoutBg.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    private fun initTab(tabList: MutableList<TvTabBean>) {
        // 代码动态添加tab
        for (i in tabList.indices) {
            binding.tablayout.addTab(binding.tablayout.newTab().setText(tabList[i].name), i == 1)
        }
        binding.tablayout.addOnTabSelectedListener(object : TvTabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TvTabLayout.Tab?) {
                LogUtils.d(LogCat.LOG_COMMONON + " position " + tab?.position)
                tab?.position?.let { fragment.setNewUrl(it) }
//                if (tab?.position == 0) {
//                    fragment.setNewUrl(THOUSANDS_URL)
//                } else if (tab?.position == 1) {
//                    fragment.setNewUrl(THOUSANDS_URL1)
//                } else if (tab?.position == 2) {
//                    fragment.setNewUrl(THOUSANDS_URL2)
//                }
            }

            override fun onTabUnselected(tab: TvTabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TvTabLayout.Tab?) {
            }

        })
        //请求焦点
        binding.tablayout.requestFocus()
    }

    override fun initData() {
        getTabMenu()

    }


//    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
//
//        return super.onKeyDown(keyCode, event)
//    }

    override fun onBackPressed() {
//        super.onBackPressed()
        LogUtils.d(LogCat.LOG_COMMONON + "---onBackPressed----  ")
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        LogUtils.d(LogCat.LOG_COMMONON + "---keyCode----$keyCode  action ${event?.action}")
        if (binding.tablayout.isVisible) {
            //显示做倒计时 ，不显示不要做倒计时了。。
            initCountDown()
        }
        initCountDown()
        when (keyCode) {
            KeyEvent.KEYCODE_MENU -> {
                changeTabState(true)
                //请求焦点
                binding.tablayout.requestFocus()
                LogUtils.d(LogCat.LOG_COMMONON + "---显示tab----  ")

            }
            KeyEvent.KEYCODE_BACK -> {
                //显示弹框
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .hasShadowBg(true)
                    .asCustom(
                        NoticePopupWindow(this,
                            object : NoticePopupWindow.OnClickQuiteLister {
                                override fun quite() {
                                    finish()
                                }

                                override fun switch() {
                                    //切换账号
                                    HttpClient.get()[AppConstant.getApiAddress() + ApiAddress.AUTH_LOGOUT, emptyMap(), object :
                                        RxObserver() {
                                        override fun onSuccess(t: JsonElement) {
                                            LogUtils.d(LogCat.LOG_COMMONON+" 切换账号。。。。  ${t}")
                                            JumpHelper.gotoLoginActivity()
                                            finish()
                                        }
                                    }]

                                }

                            })
                    )
                    .show()
//                finish()
            }

        }
        return super.onKeyDown(keyCode, event)
    }

    fun getTabMenu() {
        val map = mutableMapOf<String, Any>()
        map["type"] = 2
        HttpClient.get()[ApiAddress.TV_TAB_MODELROLEDEFAULT, map, object : RxObserver() {
            override fun onSuccess(t: JsonElement?) {
                val data = GsonUtils.covertArray(
                    t,
                    TvTabBean::class.java
                ).data
                if (data != null && data.size > 0) {
                    for (i in data.indices) {
                        tabList.add(i, data[i])
                    }
                }
                HttpClient.get()[ApiAddress.TV_TAB_MODELROLEDEFAULT2, map, object : RxObserver() {
                    override fun onSuccess(t: JsonElement?) {
                        val data = GsonUtils.covertArray(
                            t,
                            TvTabBean::class.java
                        ).data
                        if (data != null && data.size > 0) {
                            for (i in data.indices) {
                                tabList.add(i, data[i])
                            }
                        }
                        LogUtils.d(LogCat.LOG_COMMONON + "tabList ${tabList.size}")
                        changeTabState(true)
                        initTab(tabList)
                    }

                }]
            }

        }]
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != countDownTimer) {
            countDownTimer?.cancel()
            countDownTimer = null
        }
    }

}